import 'reflect-metadata'
import fs from 'fs'
import path from 'path'
import { Request, Response, NextFunction } from 'express'
import { controller, use, get } from '../decorator'
import { getResponseData } from '../utils/util'
import Crowller from '../utils/demo'
import Analyze from '../utils/Analyzer'

interface CourseItem {
  title: string
  count: number
}
interface DataStructure {
  [key: string]: CourseItem[]
}
interface BodyRequest extends Request {
  body: {
    [key: string]: string | undefined
  }
}
// 登录中间件 检测权限
const cheekLogin = (req: Request, res: Response, next: NextFunction): void => {
  const islogin = !!(req.session ? req.session.login : false)
  if (islogin) {
    next()
  } else {
    res.json(getResponseData(null, '请先登录'))
  }
}

@controller('/api')
export class CrowllerController {
  @get('/getData')
  @use(cheekLogin)
  getData(req: BodyRequest, res: Response): void {
    const url = 'http://www.dell-lee.com/typescript/demo.html?secret=x3b174jsx'
    const analyzer = Analyze.getInstance()
    new Crowller(url, analyzer)
    res.json(getResponseData<boolean>(true))
  }
  @get('/showData')
  @use(cheekLogin)
  showData(req: BodyRequest, res: Response): void {
    try {
      const positon = path.resolve(__dirname, '../../data/course.json')
      const result = fs.readFileSync(positon, 'utf-8')
      res.json(getResponseData<DataStructure>(JSON.parse(result)))
    } catch (error) {
      res.json(getResponseData<boolean>(false, '数据不存在'))
    }
  }
}
